<?php

namespace App\Http\Controllers\Api;

use App\Models\Book;
use App\Models\Chapter;
use Illuminate\Http\Request;
use App\Http\Resources\Chapter as ChapterCollection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;

class ChaptersController extends ApiController
{

    public function __construct()
    {
        $this->middleware('auth:api')->only([
            'store'
        ]);
    }

    /**
     *
     * @api {get} /books/:book/chapters 获取章节
     * @apiName Chapters get chapters
     * @apiGroup Chapter
     *
     * @apiParam {String} book 书籍的id
     * @apiParam {String} [limit] 倒序获取最后更新的章节
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/books/:book/chapters
     *
     */
    public function index(Book $book){

        $limit = Input::get('limit');

        if ($limit){

            $chapters = $book->chapters()->normal()->orderBy('last_modify_time','desc')->paginate($limit);

            return ChapterCollection::collection($chapters);
        }


        $chapters = $book->chapters()->normal()->get();

        return ChapterCollection::collection($chapters);

    }



    /**
     *
     * @api {post} /books/:book/chapters 添加章和卷
     * @apiName Chapters posts chapters
     * @apiGroup Chapter
     *
     * @apiParam {String} book 书籍的id
     * @apiParam {String} name 章卷的名字
     * @apiParam {String} type 章卷类型 0=>章,1=>卷
     * @apiParam {String} [pid] 章所对卷的id
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/books/:book/chapters
     *
     */
    public function store(Request $request,Book $book){


        if ($book->creater->id !== Auth::user()->id){
            return $this->failed('没有权限');
        }

        $this->validate($request,[
            'name' => 'required',
            'type' => 'required|integer|between:0,1',
            'pid' => 'exists:chapter,id'
        ]);

        // 将pid 变成 章节编号
        if ($request->has('pid')){

            $chapter = Chapter::find($request->pid);
            $request->offsetUnset('pid');
            $request->offsetSet('pid',$chapter->chapter_num);

        }

        // 创建卷
        if($request->type == 1){

            $last = $book->chapters()->where('type',1)->latest()->first();
            $indexes = 0;
            if ($last){
                $indexes = $last->indexes + 1;
            }

            $request->offsetSet('indexes',$indexes);

            $chapter = $book->chapters()->create( $request->all() );
        }else{

            $builder = $book->chapters();
            // 创建章
            if ($request->has('pid')){
                $builder->where('pid',$request->pid);
            }
            $last = $builder->where('type',0)->latest()->first();
            $indexes = 0;
            if ($last){
                $indexes = $last->indexes + 10000;
            }

            $request->offsetSet('indexes',$indexes);

            $chapter = $book->chapters()->create( $request->all() );
        }

        return $chapter;
    }



}
